package controle;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import net.sf.jColtrane.annotations.methods.ContainAttribute;
import net.sf.jColtrane.annotations.methods.EndElement;
import net.sf.jColtrane.annotations.methods.InsideElement;
import net.sf.jColtrane.annotations.methods.StartElement;
import net.sf.jColtrane.handler.ContextVariables;
import net.sf.jColtrane.handler.SAXEvent;

import org.xml.sax.helpers.DefaultHandler;

public class GeraDocumentosXmltv extends DefaultHandler{
	StringBuffer documento_xmltv = new StringBuffer().append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
	File arquivo; //nome do arquivo a ser gravado

	@StartElement
	@InsideElement(tag = "programme")
	public void inicioInsidePrograma(ContextVariables vars) {
		SAXEvent event = vars.getLastEvent();
		
		documento_xmltv.append("<");
		documento_xmltv.append(event.getTag());
		documento_xmltv.append(" ");
		for (String qName : event.getAtributesHolder().getQNames()) {
			documento_xmltv.append(qName);
			documento_xmltv.append("=\"");
			documento_xmltv.append(event.getAtributesHolder().getValue(qName));
			documento_xmltv.append("\" ");
		}
		documento_xmltv.append(">\n");

	}

	@EndElement
	@InsideElement(tag = "programme", attributes = { @ContainAttribute(name = "event_id") })
	public void fimInsidePrograma(ContextVariables vars) {
		SAXEvent event = vars.getLastEvent();
		if (!vars.getBody().equals("")){
			documento_xmltv.append(vars.getBody());
			documento_xmltv.append("\n");
		}
		documento_xmltv.append("</");
		documento_xmltv.append(event.getTag());
		documento_xmltv.append(">\n");
		if (event.getTag() == "programme") {
			String idEventoString = event.getAtributesHolder().getValue("event_id");
			try{
				if(!idEventoString.equals("")){
					File arquivo= new File(".\\files\\arquivos_xmltv_por_programa\\"+idEventoString+".xml");
					BufferedWriter out = new BufferedWriter(new FileWriter(arquivo));
					out.write(documento_xmltv.toString());
					out.close();
				}
				
			} catch (IOException e) {
				System.err.println(e.getMessage());
			}
				documento_xmltv.setLength(0);
				documento_xmltv.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n");
		}
	}
}
